//
//  FCCustomerRelationViewController_1_1.m
//  AFNetworking
//
//  Created by 陈文斌 on 2019/5/21.
//

#import "FCCustomerRelationViewController_1_1.h"
#import "CustomerRelationHeader.h"
#import "FCAddRelationViewController.h"
#import "FCSearchRelationViewController.h"
#import "FCRelationTypeTableViewCell.h"
#import "FCCustomerRelationRequest.h"
#import "FCRelationTypeListModel.h"
#import "FCRelationListModel.h"
#import "FCRelationTableViewCell.h"
#import "FCRelationCompanyDetailViewController.h"
#import "FCRelationTypeManagerViewController.h"
#import "FCEmptyView.h"
#import "UIViewController+Permiss.h"

#import "FCRelationGroupManagerViewController.h"
#import "FCCrmSupplyRelationOnlyTypeManagerModel.h"

@interface FCCustomerRelationViewController_1_1 ()<UITableViewDataSource, UITableViewDelegate>
// 导航栏底部黑线
@property (nonatomic, strong) UIImageView *navBarHairlineImageView;
// 搜索
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) UIView *leftView;
@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) NSMutableArray<FCRelationTypeModel *> *relationTypes;
@property (nonatomic, strong) NSMutableDictionary *dataDic;
@property (nonatomic, strong) UITableView *rightTableView;
@property (nonatomic, assign) Boolean isScrollDown;
@property (nonatomic, assign) Boolean isLoadDetail;
@property (nonatomic, assign) Boolean isUpdateData;

@property (nonatomic, strong) NSMutableArray<FCRelationTypeModel *> *newRelationTypes;
@property (nonatomic, strong) NSMutableDictionary * newDataDic;

@property (nonatomic, strong) NSIndexPath *saveSelIndexPath;

@property (nonatomic, strong) UIView *netView;

@end

@implementation FCCustomerRelationViewController_1_1

- (NSMutableArray<FCRelationTypeModel *> *)newRelationTypes{
    if (!_newRelationTypes) {
        _newRelationTypes = [NSMutableArray array];
    }
    return _newRelationTypes;
}
- (NSMutableDictionary *)newDataDic{
    if (!_newDataDic) {
        _newDataDic = [NSMutableDictionary dictionary];
    }
    return _newDataDic;
}
- (NSMutableDictionary *)dataDic{
    if (!_dataDic) {
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}
- (NSMutableArray *)relationTypes{
    if (!_relationTypes) {
        _relationTypes = [NSMutableArray array];
    }
    return _relationTypes;
}

- (NSIndexPath *)saveSelIndexPath{
    if (!_saveSelIndexPath) {
        _saveSelIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    }
    return _saveSelIndexPath;
}

// 创建导航按钮
- (UIBarButtonItem *)itemWithColor:(UIColor *)color highColor:(UIColor *)highColor target:(id)target action:(SEL)action title:(NSString *)title{
    UIView *containerView = [UIView new];
    containerView.frame = (CGRect){.size = CGSizeMake(80, 28)};
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = containerView.bounds;
    [button.titleLabel setFont:font14];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    [button setTitleColor:highColor forState:UIControlStateHighlighted];
//    [button sizeToFit];
//    button.contentEdgeInsets = UIEdgeInsetsMake(4, 8, 6, 7);
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundColor:FCWhiteColor];
//    button.layer.cornerRadius = 4;
    return  [[UIBarButtonItem alloc] initWithCustomView:button];
}

// 初始化UI
- (void)setupUI{
    self.title = customerRelationLocaChanged(@"关系管理", @"关系管理");
    self.view.backgroundColor = FCWhiteColor;
    
    // 导航栏添加上下游按钮
//    if (self.isBoss) {
//        UIBarButtonItem *addBarBut = [self itemWithColor:FCBlueTxtColor highColor:FCBlueTxtColor target:self action:@selector(addRelationTypeAction) title:customerRelationLocaChanged(@"分组管理", @"分组管理")];
//        self.navigationItem.rightBarButtonItems = @[addBarBut];
//    }
    UIBarButtonItem *addBarBut = [self itemWithColor:FCBlueTxtColor highColor:FCBlueTxtColor target:self action:@selector(addRelationTypeAction) title:customerRelationLocaChanged(@"分组管理", @"分组管理")];
    self.navigationItem.rightBarButtonItems = @[addBarBut];
    
    self.searchView = [[UIView alloc] init];
    [self.view addSubview:_searchView];
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.and.right.mas_equalTo(0);
        make.height.mas_equalTo(48);
    }];
    _searchView.backgroundColor = [UIColor whiteColor];
    _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_searchView addSubview:_searchBtn];
    [_searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(30);
    }];
    _searchBtn.titleLabel.font = font13;
    _searchBtn.backgroundColor = FCBackColor;
    _searchBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    _searchBtn.layer.cornerRadius = 4;
    _searchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_searchBtn setImage:customerRelationImageName(@"nav_ic_search_g") forState:UIControlStateNormal];
    [_searchBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 12, 0, 0)];
    [_searchBtn setTitle:customerRelationLocaChanged(@"global_general_search", @"搜索") forState:UIControlStateNormal];
    [_searchBtn setTitleColor:FCGrayTxtPlaceColor forState:UIControlStateNormal];
    [_searchBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 18, 0, 0)];
    [_searchBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark - 添加上下游关系
- (void)addAction{
    WJCWeakSelf
    [self checkPermissionWithCode:@"Crm:Relations.Add" andReturnBlock:^(FCPermissSubCellModel *permission) {
        if (permission.isAllowedByCurrIdentity) {
            if ([FCEmployeeModel isBusinessWithNotice:YES andPushController:weakSelf]) {
                FCAddRelationViewController *addRelattionVC = [[FCAddRelationViewController alloc] init];
                [weakSelf.navigationController pushViewController:addRelattionVC animated:YES];
            }
        } else {
            weakSelf.permissionCode=@"Crm:Relations.Add";
            [weakSelf checkPermissionandReturnBlock:^(FCPermissSubCellModel * _Nonnull permission) {
                
            }];
            return;
        }
    }];
}

#pragma mark - 搜索上下游关系
- (void)searchAction {
    FCSearchRelationViewController *searchRelationVC = [[FCSearchRelationViewController alloc] init];
    [self.navigationController pushViewController:searchRelationVC animated:NO];
}

#pragma mark - 获取导航栏黑线
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    
    return nil;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    _navBarHairlineImageView.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    _navBarHairlineImageView.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupNotification];
    [self createLeftTableView];
    [self createRightTableView];
    [self getCacheData];
    [self setupEmptyView];
    [self setupNotification];
    [self setupNetView];
}

- (void)setupEmptyView
{
    NSString *title = [NSString stringWithFormat:@"没有相关数据"];
    NSString *imageName = @"ic_empty_photo_customer";
    FCEmptyView *emptyView = [FCEmptyView emptyViewWithTitle:title imageName:imageName btnTitle:nil target:self action:nil];
    self.rightTableView.ly_emptyView = emptyView;
    [self setEmptyView];
}

#pragma mark - 设置空白页显示与隐藏
- (void)setEmptyView
{
    [self.rightTableView reloadData];
    BOOL isShow;
    for (NSArray *relation in self.dataDic.allValues) {
        if (relation.count > 0) {
            isShow = YES;
        }
    }
    
    if (isShow) {
        [self.rightTableView ly_hideEmptyView];
    } else {
        [self.rightTableView ly_showEmptyView];
    }
}

#pragma mark - 创建左侧列表
#define RelationCell @"FCRelationTableViewCell"

- (void)createLeftTableView{
    self.leftView = [UIView new];
    [self.view addSubview:_leftView];
    WJCWeakSelf
    [_leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom).mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_offset(88);
    }];
    _leftView.backgroundColor = FCStatuSimpleGrayColor;
    
    UIView *addRelationView = [[UIView alloc] init];
    [_leftView addSubview:addRelationView];
    [addRelationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(0);
        make.height.mas_equalTo(60);
        make.bottom.mas_equalTo(-FCTabbarSafeBottomMargin);
    }];
//    UITapGestureRecognizer *click = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addRelationTypeAction)];
//    [addRelationTypeBtn addGestureRecognizer:click];
    
//    UILabel *btnTitle = [UILabel new];
//    [addRelationTypeBtn addSubview:btnTitle];
//    [btnTitle mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.mas_equalTo(-16);
//        make.left.and.right.mas_equalTo(0);
//    }];
//    btnTitle.text = @"关系类型管理";
//    btnTitle.font = font11;
//    btnTitle.textColor = FCBlueTxtColor;
//    btnTitle.textAlignment = NSTextAlignmentCenter;
    
//    UIImageView *btnImage = [UIImageView new];
//    [addRelationTypeBtn addSubview:btnImage];
//    [btnImage mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(0);
//        make.bottom.equalTo(btnTitle.mas_top).mas_equalTo(-3);
//        make.height.mas_equalTo(24);
//        make.width.mas_equalTo(24);
//    }];
//    btnImage.image = customerRelationImageName(@"ic_relation_group_manage");
    
    UIButton *addRelationButton = [UIButton new];
    [addRelationView addSubview:addRelationButton];
    [addRelationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(4);
        make.top.mas_offset(16);
        make.bottom.mas_offset(-16);
        make.right.mas_offset(-4);
    }];
    [addRelationButton setBackgroundColor:FCBackBlueColor];
    [addRelationButton.titleLabel setFont:font13];
    [addRelationButton setTitle:@"添加上下游" forState:UIControlStateNormal];
    [addRelationButton setTitleColor:FCWhiteColor forState:UIControlStateNormal];
    [addRelationButton setTitleColor:FCWhiteColor forState:UIControlStateHighlighted];
    [addRelationButton addTarget:self action:@selector(addAction) forControlEvents:UIControlEventTouchUpInside];
    addRelationButton.layer.cornerRadius = 4;
    
    self.leftTableView = [UITableView new];
    [_leftView addSubview:self.leftTableView];
    [self.leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.and.right.mas_equalTo(0);
        make.bottom.equalTo(addRelationView.mas_top).mas_equalTo(0);
    }];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.backgroundColor = FCStatuSimpleGrayColor;
    self.leftTableView.separatorStyle = UITableViewCellEditingStyleNone;
    self.leftTableView.estimatedRowHeight = 0;
    self.leftTableView.estimatedSectionHeaderHeight = 0;
    self.leftTableView.estimatedSectionFooterHeight = 0;
}

- (void)createRightTableView{
    self.rightTableView = [UITableView new];
    [self.view addSubview:self.rightTableView];
    WJCWeakSelf
    [self.rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.searchView.mas_bottom).mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(WJCScreenW - 88);
    }];
    self.rightTableView.separatorStyle = UITableViewCellEditingStyleNone;
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    [self.rightTableView registerNib:[UINib nibWithNibName:NSStringFromClass([FCRelationTableViewCell class]) bundle:nil] forCellReuseIdentifier:RelationCell];
    [self setExtraCellLineHidden:self.rightTableView];
    self.rightTableView.estimatedRowHeight = 0;
    self.rightTableView.estimatedSectionHeaderHeight = 0;
    self.rightTableView.estimatedSectionFooterHeight = 0;
}

- (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    [tableView setTableFooterView:view];
}

#pragma mark - 分组管理
- (void)addRelationTypeAction{
    XMGLog(@"分组管理");
    if (![FCEmployeeModel empCompanyIsMine]) {
        WJCWeakSelf
        [self checkPermissionWithCode:@"Crm:Relations.View" andReturnBlock:^(FCPermissSubCellModel *permission) {
            if (permission.isAllowedByCurrIdentity) {
                if ([FCEmployeeModel isBusinessWithNotice:YES andPushController:self]) {
                    //        FCRelationTypeManagerViewController *relationTypeManagerVC = [[FCRelationTypeManagerViewController alloc] init];
                    //        [self.navigationController pushViewController:relationTypeManagerVC animated:YES];
                    FCRelationGroupManagerViewController *groupManagerVC = [[FCRelationGroupManagerViewController alloc] init];
                    [self.navigationController pushViewController:groupManagerVC animated:YES];
                }
            } else {
                weakSelf.permissionCode=@"Crm:Relations.View";
                [weakSelf checkPermissionandReturnBlock:^(FCPermissSubCellModel * _Nonnull permission) {
                    
                }];
                return;
            }
        }];
    } else {
        if ([FCEmployeeModel isBusinessWithNotice:YES andPushController:self]) {
            //        FCRelationTypeManagerViewController *relationTypeManagerVC = [[FCRelationTypeManagerViewController alloc] init];
            //        [self.navigationController pushViewController:relationTypeManagerVC animated:YES];
            FCRelationGroupManagerViewController *groupManagerVC = [[FCRelationGroupManagerViewController alloc] init];
            [self.navigationController pushViewController:groupManagerVC animated:YES];
        }
    }
}

#pragma mark - tableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(tableView == self.rightTableView){
        return self.relationTypes.count + 1;
    }
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.rightTableView) {
        if (self.relationTypes.count == section) {
            CGFloat height = 0;
            NSMutableArray *saveArr = [NSMutableArray array];
            for (FCRelationModel *type in self.relationTypes) {
                NSArray *arr = self.dataDic[type.Id];
                if (arr.count) {
                    saveArr = arr;
                }
            }
            
            for (FCRelationModel *groupModel in saveArr) {
                height += (IphonePlus ? 52 : 48);
            }
            
            return self.rightTableView.height - height - (IphonePlus ? 52 : 48);
        } else {
            FCRelationTypeModel *relationType = self.relationTypes[section];
            NSArray *relations = self.dataDic[relationType.Id];
            if (relations.count == 0) {
                return 0;
            }
            if (IphonePlus) {
                return 52;
            } else{
                return 48;
            }
        }
    }
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.rightTableView) {
        if (section == self.relationTypes.count) {
            return [UIView new];
        }
        UIView *headerView = [UIView new];
        headerView.backgroundColor = FCWhiteColor;
        UILabel *sectionTitleLabel = [UILabel new];
        [headerView addSubview:sectionTitleLabel];
        [sectionTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
            make.right.mas_equalTo(-16);
            make.centerY.mas_equalTo(0);
        }];
        
        FCRelationTypeModel *relationType = self.relationTypes[section];
        sectionTitleLabel.text = relationType.name;
        sectionTitleLabel.font = font12;
        sectionTitleLabel.textColor = FCGrayTxtDetailColor;
        
        return headerView;
    }
    
    return [UIView new];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == self.rightTableView){
        if (section == self.relationTypes.count) {
            return 0;
        }
        NSMutableArray *relations = self.dataDic[self.relationTypes[section].Id];
        return relations.count;
    }
    return self.relationTypes.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (IphonePlus) {
        return 54;
    } else{
        return 48;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == self.relationTypes.count) {
        return FCTabbarSafeBottomMargin;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [UIView new];
    footerView.backgroundColor = FCWhiteColor;
    
    return footerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.leftTableView) {
        FCRelationTypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[FCRelationTypeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            [tableView setSeparatorColor: FCLineColor];
        }
        if (self.saveSelIndexPath == indexPath) {
            [tableView selectRowAtIndexPath:self.saveSelIndexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        }
        FCRelationTypeModel *relationType = self.relationTypes[indexPath.row];
        NSArray *relation = self.dataDic[relationType.Id];
        [cell setText:[NSString stringWithFormat:@"%@(%ld)",relationType.name, relation.count]];
        
        return cell;
    } else {
        FCRelationTypeModel *relationType = self.relationTypes[indexPath.section];
        NSMutableArray *relations = self.dataDic[relationType.Id];
        FCRelationModel *relation = relations[indexPath.row];
        
        FCRelationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RelationCell forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSString *companyNameStr = relation.rel.BrandName ?: relation.relCompanyName;
        cell.companyName.text = companyNameStr;
        
        [cell setAreaInfoWithResidentProvince:relation.rel.ResidentProvince ?: @"" ResidentArea:relation.rel.ResidentCity ?: @"" Status:relation.status];
        [cell setStatusStyleWithStatus:relation.status];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.leftTableView) {
        FCRelationTypeModel *relationType = self.relationTypes[indexPath.row];
        NSArray *relations = self.dataDic[relationType.Id];
        if (relations.count == 0) {
            return;
        }
        NSIndexPath *moveIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        self.saveSelIndexPath = indexPath;
        [self.rightTableView scrollToRowAtIndexPath:moveIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    if (tableView == self.rightTableView){
        if (!self.isLoadDetail) {
            self.isLoadDetail = YES;
            FCRelationTypeModel *relationType = self.relationTypes[indexPath.section];
            NSMutableArray *relations = self.dataDic[relationType.Id];
            FCRelationModel *relation = relations[indexPath.row];
            
            NSDictionary *args = @{
                                   @"id": relation.Id,
                                   @"companyId": relation.relId
                                   };
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
            //            [SVProgressHUD show];
            WJCWeakSelf
            [FCCustomerRelationRequest getRelationDetailWithArgs:args success:^(id resultObj) {
                FCRelationModel *relationModel = [FCRelationModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationGet"]];
                FCRelationCompanyDetailViewController *relationBindRequestVC = [[FCRelationCompanyDetailViewController alloc] init];
                relationBindRequestVC.relation = relationModel;
                [weakSelf.navigationController pushViewController:relationBindRequestVC animated:YES];
                [SVProgressHUD dismiss];
                weakSelf.isLoadDetail = NO;
            } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
                weakSelf.isLoadDetail = NO;
            }];

            
//            FCRelationCompanyDetailViewController *relationBindRequestVC = [[FCRelationCompanyDetailViewController alloc] init];
////            relationBindRequestVC.relation = relationModel;
//            relationBindRequestVC.relationId = relation.Id;
//            relationBindRequestVC.compangyId = relation.relId;
//            [self.navigationController pushViewController:relationBindRequestVC animated:YES];
        }
    }
}

// TableView分区标题即将展示
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section
{
    // RightTableView滚动的方向向上
    if ((self.rightTableView == tableView) && !self.isScrollDown && (self.rightTableView.dragging || self.rightTableView.decelerating)) {
        
//        [self selectRowAtIndexPath:section];
    }
}

// TableView分区标题展示结束
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // RightTableView滚动的方向向下
    if ((self.rightTableView == tableView) && self.isScrollDown && (self.rightTableView.dragging || self.rightTableView.decelerating)) {
        
//        [self selectRowAtIndexPath:section + 1];
    }
}

// 当拖动右边TableView的时候，处理左边TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    self.saveSelIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.leftTableView selectRowAtIndexPath:self.saveSelIndexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetY = scrollView.contentOffset.y;
    
    // 标记一下rightTableView的滚动方向，是向上还是向下
    static CGFloat lastOffsetY = 0;
    
    UITableView *tableView = (UITableView *)scrollView;
    if (self.rightTableView == tableView) {
//        XMGLog(@"right-offsetY %fl",offsetY);
        
        self.isScrollDown = lastOffsetY < offsetY;
        lastOffsetY = scrollView.contentOffset.y;
    }
    
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == self.leftTableView) {
        return;
    }

    if(decelerate == NO){
        [self scrollViewDidEndDecelerating:scrollView];
    }
}

- (void)scrollViewDidEndDecelerating:(nonnull UIScrollView *)scrollView{
    if (scrollView == self.rightTableView) {
        NSIndexPath *topIndexPath = [[self.rightTableView indexPathsForVisibleRows]firstObject];
        NSIndexPath *moveIndexPath = [NSIndexPath indexPathForRow:topIndexPath.section inSection:0];
        if (self.relationTypes.count > topIndexPath.section) {
            self.saveSelIndexPath = moveIndexPath;
            [self.leftTableView selectRowAtIndexPath:moveIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        }
    }
}

#pragma mark - 刷新数据
- (void)setupNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData) name:CrmSupplyRelationChanged object:nil];
}

#pragma mark - 获取数据
// 刷新数据
- (void)updateData{
    if (!self.isUpdateData) {
        self.netView.hidden = YES;
        self.isUpdateData = YES;
        // 清除旧数据
        [self.newRelationTypes removeAllObjects];
        [self.newDataDic removeAllObjects];
        // 加载新数据
        [self getRelationType];
    }
}

// 获取缓存数据
- (void)getCacheData{
    //获取缓存数据
    NSMutableDictionary *relationTypeParam = [NSMutableDictionary dictionary];
    relationTypeParam[@"isManage"] = @"YES";
    NSArray *cache = [FCFuChengCacheTool getHttpCacheWithUrlString:FCCrmSupplyRelationTypesDataKey parameters:relationTypeParam];
    NSMutableArray *cacheResult = [FCRelationTypeModel mj_objectArrayWithKeyValuesArray:cache];
    if (cacheResult.count) {
        self.newRelationTypes = cacheResult;
        self.relationTypes = [[NSMutableArray alloc] initWithArray:self.newRelationTypes];
        [self.leftTableView reloadData];
        for (FCRelationTypeModel *relationType in cacheResult) {
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[@"employeeIdAndModel"] = [NSString stringWithFormat:@"%@%@",[FCEmployeeModel getMinieEmpId],@"1"];
            NSArray *relationCache = [FCFuChengCacheTool getHttpCacheWithUrlString:relationType.Id parameters:param];
            NSMutableArray *cacheRelationResult = [FCRelationModel mj_objectArrayWithKeyValuesArray:relationCache];
            if (cacheRelationResult.count) {
                [self.newDataDic setObject:cacheRelationResult forKey:relationType.Id];
                self.dataDic = [[NSMutableDictionary alloc] initWithDictionary:self.newDataDic];
                [self.rightTableView reloadData];
                [self.leftTableView reloadData];
            } else {
                [self getRelationRequestListWithRelationTypeId:relationType.Id];
            }
        }
    }
    // 刷新新数据
    [self updateData];
}

// 关系类型
- (void)getRelationType{
    NSNumber *take = @(15);
    NSDictionary *args = @{@"isManage": @(YES),
                           @"enable": @(YES),
                           @"take": take,
                           @"skip": @(self.newRelationTypes.count)
                           };
    
    WJCWeakSelf
    [FCCustomerRelationRequest getCrmSupplyRelationTypeWithArgs:args success:^(id resultObj) {
        self.leftView.hidden = NO;
        self.rightTableView.hidden = NO;
        [self.view ly_hideEmptyView];
//        [self.rightTableView ly_hideEmptyView];
        
        FCRelationTypeListModel *relationTypesModel = [FCRelationTypeListModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationTypes"]];
        
        [weakSelf.newRelationTypes addObjectsFromArray:relationTypesModel.items];
        weakSelf.relationTypes = [[NSMutableArray alloc] initWithArray:weakSelf.newRelationTypes];
        [weakSelf.leftTableView reloadData];
        
        for (FCRelationTypeModel *relationType in relationTypesModel.items) {
            [weakSelf getRelationRequestListWithRelationTypeId:relationType.Id];
        }
        
        if (weakSelf.newRelationTypes.count >= relationTypesModel.pageInfo.total) {
            XMGLog(@"relationType 全部请求完成");
            self.isUpdateData = NO;
            //缓存
            NSArray *cache = [FCRelationTypeModel mj_keyValuesArrayWithObjectArray:self.newRelationTypes];
            NSMutableDictionary *relationTypeParam = [NSMutableDictionary dictionary];
            relationTypeParam[@"isManage"] = @"YES";
            [FCFuChengCacheTool saveHttpCache:cache urlString:FCCrmSupplyRelationTypesDataKey parameters:relationTypeParam];
        } else {
            XMGLog(@"relationType 继续请求");
            [self getRelationType];
        }
        
    } failure:^(NSError *error) {
        if (self.relationTypes.count == 0) {
            NSString *title = [NSString stringWithFormat:@"没有相关数据"];
            NSString *imageName = @"ic_empty_photo_customer";
            FCEmptyView *emptyView = [FCEmptyView emptyViewWithTitle:title imageName:imageName btnTitle:nil target:self action:nil];
            self.view.ly_emptyView = emptyView;
            self.relationTypes = nil;
            self.dataDic = nil;
            [self.leftTableView reloadData];
            [self.rightTableView reloadData];
            self.leftView.hidden = YES;
            self.rightTableView.hidden = YES;
            [self.view ly_showEmptyView];
        }
        
        self.netView.hidden = NO;
        
        _isUpdateData = NO;
        [SVProgressHUD dismiss];
        XMGLog(@"%@", error);
    }];
}

// 关系请求列表
- (void)getRelationRequestListWithRelationTypeId:(NSString *)relationTypeId{
    NSMutableArray *relationArr = [NSMutableArray array];
    if (self.newDataDic[relationTypeId]) {
        [relationArr addObjectsFromArray:self.newDataDic[relationTypeId]];
    }
    
    NSNumber *take = @(20);
    
    NSDictionary *args = @{@"skip": @(relationArr.count),
                           @"take": take,
                           @"model": @(1),
                           @"orderBy": @"status_desc",
                           @"typeId": relationTypeId};
    WJCWeakSelf
    [FCCustomerRelationRequest getRelationRequestsWithArgs:args success:^(id resultObj) {
        FCRelationListModel *relationsModel = [FCRelationListModel mj_objectWithKeyValues: resultObj[@"data"][@"crmSupplyRelations"]];
        [relationArr addObjectsFromArray:relationsModel.items];
        [weakSelf.newDataDic setObject:relationArr forKey:relationTypeId];
        
        
        //缓存
        if (relationTypeId.length) {
            NSArray *cache = [FCRelationModel mj_keyValuesArrayWithObjectArray:relationsModel.items];
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[@"employeeIdAndModel"] = [NSString stringWithFormat:@"%@%@",[FCEmployeeModel getMinieEmpId],@"1"];

            [FCFuChengCacheTool saveHttpCache:cache urlString:relationTypeId parameters:param];
        }
        
        if(relationArr.count >= relationsModel.pageInfo.total){
            XMGLog(@"%@：全部请求完成  == %@",relationTypeId, relationArr);
            [weakSelf.dataDic setObject:[[NSMutableArray alloc] initWithArray:weakSelf.newDataDic[relationTypeId]] forKey:relationTypeId];
            [weakSelf.leftTableView reloadData];
            [weakSelf.rightTableView reloadData];
            self.netView.hidden = YES;
        } else {
            XMGLog(@"%@：继续请求  %zd == %zd",relationTypeId,relationArr.count, relationsModel.pageInfo.total);
            [weakSelf getRelationRequestListWithRelationTypeId:relationTypeId];
            [weakSelf.rightTableView reloadData];
        }
        
    } failure:^(NSError *error) {
        if(self.dataDic.allKeys == 0){
            self.dataDic = nil;
            [self.rightTableView reloadData];
            NSString *title = [NSString stringWithFormat:@"网络加载异常"];
            NSString *imageName = @"ic_empty_photo_customer";
            FCEmptyView *emptyView = [FCEmptyView emptyViewWithTitle:title imageName:imageName btnTitle:@"重新加载关系" target:self action:@selector(updateData)];
            self.rightTableView.ly_emptyView = emptyView;
            [self.rightTableView ly_showEmptyView];
        }
        self.netView.hidden = NO;
        [SVProgressHUD dismiss];
    }];
}

- (void)refreshWorkData{
    self.leftView.hidden = NO;
    self.rightTableView.hidden = NO;
    [self.view ly_hideEmptyView];
    [self.rightTableView ly_hideEmptyView];
    [self getRelationType];
}

- (void)setupNetView{
    self.netView = [UIView new];
    [self.view addSubview:_netView];
    [_netView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-FCTabbarSafeBottomMargin - FCTabbarHeight - 44);
        make.height.mas_equalTo(FCTabbarHeight);
    }];
    _netView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.75];
    UILabel *label = [UILabel new];
    [_netView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.centerY.mas_equalTo(0);
    }];
    label.font = font14;
    label.textColor = FCWhiteColor;
    label.text = @"当前页面网络加载异常";
    UIButton *button = [UIButton new];
    [_netView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-14);
        make.centerY.mas_equalTo(0);
        make.height.mas_equalTo(28);
        make.width.mas_equalTo(60);
    }];
    [button setBackgroundColor:FCBackBlueColor];
    [button setTitle:@"重新加载" forState:UIControlStateNormal];
    [button setTitleColor:FCWhiteColor forState:UIControlStateNormal];
    [button addTarget:self action:@selector(updateData) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = font12;
    FCSETLRViewBorderRadius(button, 4);
    
    _netView.hidden = YES;
}

@end
